package org.example.order.domain;

import lombok.Builder;
import lombok.Getter;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Getter
public class Order {
    private String id;
    private String orderNo;
    private Org org;
    private Customer customer;
    private List<OrderDetail> details;
    private Optional<BigDecimal> totalAmount;

    @Builder
    public Order(String id, String orderNo, Org org, Customer customer, List<OrderDetail> details) {
        this.id = id;
        this.orderNo = orderNo;
        this.org = org;
        this.customer = customer;
        setOrderDetails(details);
    }

    private Optional<BigDecimal> calcTotalAmount(List<OrderDetail> details) {
        if (details == null || details.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(details.stream().map(OrderDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
    }

    public void setDetails(List<OrderDetail> details) {
        if (details == null || details.isEmpty()) {
            throw new OrderDomainException(DomainErrorCode.ORDER_DETAIL_NOT_FOUND, this.id);
        }
        setOrderDetails(details);
    }

    private void setOrderDetails(List<OrderDetail> details) {
        this.details = details;
        this.totalAmount = calcTotalAmount(details);
    }
}
